const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const fs=require('fs');
const FileStreamRotator = require('file-stream-rotator');
const session = require('express-session');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
const cors = require('cors')
const config = require('./config')
// 路由文件
const indexRouter = require('./routes/index'); // 默认自带路由
const smsRouter = require('./routes/sms'); // 短信路由
const userRouter = require('./routes/user/user'); // 用户路由
const uploadRouter = require('./routes/upload'); // 上传路由
const exportRouter = require('./routes/export'); // 导出路由
const logRouter = require('./routes/log'); // 备忘记录路由

const testRouter = require('./routes/test/index'); // 用户路由

var app = express();


// 设置日志
//设置日志文件目录
var logDirectory=__dirname+'/logs/morgan';
//确保日志文件目录存在 没有则创建
fs.existsSync(logDirectory)||fs.mkdirSync(logDirectory);

//创建一个写路由
var accessLogStream=FileStreamRotator.getStream({
    filename:logDirectory+'/accss-%DATE%.log',
    frequency:'daily',
    verbose:false
})


app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(fileUpload({
  useTempFiles : true,
  tempFileDir : './tmp/'
}))

// 设置跨域
app.all('*', cors({
  // 配置白名单
  origin: config.URL_ARR,  //指定接收的地址
  // origin:['http://localhost:3000'],  //指定接收的地址
  methods:['*'],  //指定接收的请求类型
  credentials: true,
  alloweHeaders:['Content-Type','content-type']  //指定header
}), function (req, res, next) {
  next();
});



app.use(logger('combined',{stream:accessLogStream}));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// 设置静态文件
app.use(express.static('static'))

// 使用 session 中间件
app.use(session({
  secret :  'secret', // 对session id 相关的cookie 进行签名
  resave : true,
  saveUninitialized: false, // 是否保存未初始化的会话
  cookie : {
      maxAge : 1000 * 60 * 3, // 设置 session 的有效时间，单位毫秒
  },
}))

/* function test () {
  let task = new Promise ((resolve, reject) => {
    setTimeout(() => {
      resolve('sss')
    }, 1000)
  })
  return task
}

let pool = 'sss'
// 执行sql 方法
try {
  Promise.all([test, xx.text]).then((res) => {
    console.log(res)
    pool
  }).catch((res) => {
    console.log(res)
  })
} catch (error) {
  console.log(pool)
} */

// 使用路由文件
app.use('/', indexRouter);
app.use('/test', testRouter);
app.use('/sms', smsRouter);
app.use('/user', userRouter);
app.use('/upload', uploadRouter);
app.use('/export', exportRouter);
app.use('/log', logRouter);
module.exports = app;
